//
//  TFMarquee.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/10.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

public class TFMarquee: TalkfunHitTestView {
    @objc public weak var delegate : TFMarqueeDelegate?
 
    @objc var url:String = ""
    @objc let content = UILabel()
    @objc let view = UIView()
    let avatar = UIButton()
    let contentBackground = UIView()
    let closeWinners = TalkfunIncreaseButton()
    //定时器
    @objc var timer:Timer?
    @objc var duration:NSInteger = 0
    @objc var isHiddeView:Bool = false

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isHiddeView = true
        self.duration = 0
        self.url = ""

        self.addSubview(self.view)
        self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
        self.avatar.backgroundColor = UIColor(red: 39/255.0, green: 211/255.0, blue: 255/255.0, alpha: 0.6)
        self.avatar.setImage(UIImage.init(named: "HTLive.bundle/announcement"), for: .normal)
     
        self.view.addSubview(self.avatar)

        self.contentBackground.backgroundColor = UIColor.clear
        self.contentBackground.clipsToBounds = true
        self.view.addSubview(self.contentBackground)
      

        self.content.textAlignment = .left
        self.content.textColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255/255.0, alpha: 1)
        
          self.content.font = UIFont.systemFont(ofSize: 15)
        self.contentBackground.addSubview(self.content)
        
        self.closeWinners.setImage(UIImage.init(named: "HTLive.bundle/closeWinners"), for: .normal)
    
        self.view.addSubview(self.closeWinners)
        self.closeWinners.addTarget(self, action: #selector(closeWinnersCLick), for: .touchUpInside)
      
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc func closeWinnersCLick()
    {
        self.isHiddeView = true
        self.view.isHidden = true

        self.destroy()
    }
    @objc func destroy()
    {
        if self.timer != nil {
            self.timer!.invalidate()
            self.timer = nil
        }
    }
    @objc func timer_Action()

    {
        self.duration = self.duration-1
        if (self.duration<=0) {
            // 回到主线程更新UI
            DispatchQueue.main.async {
                   //code
                self.closeWinnersCLick()
               }
        }
    }
    @objc func refreshData()

    {

        if (self.content.text != nil && self.isHiddeView==false) {
            self.initContent(self.content.text!, link: self.url, duration: self.duration)

           }
                               

    }
    //初始化通知数据ui
    @objc func initContent(_ content:String,link:String,duration:NSInteger)

    {
        if (content.count>0) {
            self.isHiddeView = false
            self.url = ""
            if (link.count>0) {
                self.url = link
            }
            self.duration = 0
            if (duration>0) {
            self.duration = duration
            }
            self.content.layer.removeAllAnimations()
           
            self.destroy()
            if (self.duration != 0) {
                self.timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.timer_Action), userInfo: nil, repeats: true)

                RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
                
            }
           
            self.view.isHidden = false
           
            
            let attrsSize: CGSize = content.size(withAttributes: [NSAttributedString.Key.font: self.content.font])
            
            
            var viewWidth:CGFloat = 3.5+25+8+attrsSize.width+13.5+12+12
            var run:Bool = false
            if (viewWidth>self.frame.size.width) {
                viewWidth = self.frame.size.width
               run = true
            }
            self.view.layer.cornerRadius = 16
            self.view.frame = CGRect(x: (self.frame.size.width - viewWidth)/2.0, y: 0, width: viewWidth, height: self.frame.size.height)
         

            self.avatar.frame = CGRect(x: 3.5, y: (self.frame.size.height-25)/2, width: 25, height: 25)
    
            self.avatar.layer.cornerRadius = self.avatar.bounds.size.width / 2

            let contentBackgroundX:CGFloat = 3.5+25+8;

            self.contentBackground.frame = CGRect(x: contentBackgroundX, y: 0, width: self.view.frame.size.width-37.5-contentBackgroundX, height: self.view.frame.size.height)
           
            self.content.frame = CGRect(x: 0, y: 0, width: attrsSize.width, height: self.contentBackground.frame.height)
          
            self.content.text = content

            self.closeWinners.frame = CGRect(x: self.view.frame.size.width - 12 - 12, y: (self.view.frame.size.height - 12)/2, width: 12, height: 12)
           


            if (run) {
                self.content.layer.removeAllAnimations()

                self.content.layer.removeAnimation(forKey: "animationViewPosition")
                self.start_Animation()
               
               
            }
                           
          
          
            
        }
        
    }
    //跑马灯显示
    func start_Animation()
    {
        
    let movePath  = UIBezierPath()
    
    movePath.move(to: CGPoint(x: self.content.frame.size.width, y: self.content.bounds.size.height/2))
    
    movePath.addLine(to: CGPoint(x: -self.content.frame.size.width+10, y: self.content.bounds.size.height/2))

    let moveAnimation = CAKeyframeAnimation.init(keyPath: "position")

    moveAnimation.path = movePath.cgPath;
    moveAnimation.isRemovedOnCompletion = false
  
    moveAnimation.fillMode = CAMediaTimingFillMode.forwards

    let interval:CGFloat = self.content.frame.size.width / 35

    moveAnimation.duration = interval

    moveAnimation.repeatCount = Float(CGFloat.greatestFiniteMagnitude)
    self.content.layer.add(moveAnimation, forKey: "animationViewPosition")
   

    }
    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
 
        // 重点开始！！UITouch 获取在 barrageView 坐标系下的坐标
        for touch : AnyObject in touches {
            
       let t : UITouch = touch as! UITouch;
            
        let  touchPoint =  t.location(in: self.view)
      
            if ((self.content.layer.presentation()?.hitTest(touchPoint)) != nil) {
                
                if self.delegate != nil && (self.delegate?.responds(to: #selector(TF_AnnounceRollViewDelegate.marqueeClick) )   )!{
                    
                    self.delegate?.marqueeClick()
                    
                }
                return;
            }
 
        }

    }
    
    
}
@objc public protocol TFMarqueeDelegate : NSObjectProtocol {
   // 通知点距链接
    func marqueeClick()

}
